<template>
    <!-- 图表弹框 -->
    <a-modal :visible="isEcharts" @cancel="cloEchartsFn" title="可视化图表" centered width="80%" :footer="null" destroyOnClose>
        <a-form-model :model="echartsFrom" layout="inline" :colon="false">
            <a-form-model-item label="时间段" v-if="isDate">
                <a-date-picker v-model="echartsFrom.beginTime" :default-value="echartsFrom.beginTime" :disabled-date="disabledStartDate" show-time format="YYYY-MM-DD HH:mm:ss" placeholder="开始时间" @openChange="handleStartOpenChange" />
                <span style="color:#9fb043;font-size:18px;padding:0 10px;">—</span>
                <a-date-picker v-model="echartsFrom.endTime" :default-value="echartsFrom.endTime" :disabled-date="disabledEndDate" show-time format="YYYY-MM-DD HH:mm:ss" placeholder="结束时间" :open="endOpen" @openChange="handleEndOpenChange" />
            </a-form-model-item>
            <a-form-model-item label="时间分类">
                <a-radio-group v-model="echartsFrom.cn">
                    <a-radio value="2011">实时数据</a-radio>
                    <a-radio value="2051">分钟数据</a-radio>
                    <a-radio value="2061">小时数据</a-radio>
                    <a-radio value="2031">日数据</a-radio>
<!--                    <a-radio value="2031" disabled>-->
<!--                        动态管控数据-->
<!--                    </a-radio>-->
                </a-radio-group>
<!--                <a-radio-group v-model="echartsFrom.cn">-->
<!--                    <a-radio v-for="v in timeCheck" :value="v.cn" :key="v.id">{{v.name}}</a-radio>-->
<!--                </a-radio-group>-->
            </a-form-model-item>
            <a-form-model-item>
                <a-button @click="sousuo" type="primary">搜索</a-button>
            </a-form-model-item>
          <a-form-model-item v-if="faultData.status === 'D'" style="float:right;margin-right: 0">
            <a-button type="primary" @click="openFaultReport">故障上传</a-button>
          </a-form-model-item>
        </a-form-model>
        <div class="echar-table">
            <a-table :data-source="TableData" :scroll="{ x: 600, y: 250 }" :pagination="false" :rowKey="record=> record.datetime" size="middle" :loading="isloading">
                <a-table-column title="监测时间" data-index="datetime" align="center" :ellipsis="true" width="200px" />
                <a-table-column v-for="(v,i) in monitorData" :key="i" :title="v.monitorFactorsName+'('+v.unit+')'" :data-index="v.monitorFactorsCode" width="150px" align="center" :ellipsis="true" />
            </a-table>
        </div>
        <div class="content-bottom clearfix">
            <div class="page-box">
                <a-pagination :show-total="total => `共${total}条记录`" v-model="tableFrom.current" :total="total" :defaultPageSize="tableFrom.size" :item-render="itemRender" @change="pagechangeFn" hideOnSinglePage />
            </div>
        </div>
        <a-form-model :model="echartsFrom" layout="inline" :colon="false">
            <a-form-model-item label="警告类型">
                <a-radio-group v-model="echartsFrom.sampleType" @change="radioChange">
                    <a-radio :value="v.monitorFactorsCode" v-for="(v,i) in monitorData" :key="i">{{v.monitorFactorsName}}</a-radio>
                </a-radio-group>
            </a-form-model-item>
        </a-form-model>
        <div class="line-echarts" ref="lineecharts"></div>
      <fault-report ref="faultreport"></fault-report>
    </a-modal>
</template>

<script>
import moment from "moment";
import echarts from "echarts";
import FaultReport from "@/views/air/components/FaultReport";

export default {
    components:{
      FaultReport
    },
    props: {
        // monitorData: Array,
        isDate: { type: Boolean, required: false, default: true },
        faultData:{type:Object,required: false, default: ()=>{return {status: "N"}}}
    },
    data() {
        return {
            isEcharts: false,
            total: 0,
            isloading: true,
            TableData: [],
            endOpen: false, // 日期组件关联弹窗
            echartsData: [], // 表格数据
            tableFrom: {
                cn: "2011",
                mn: "",
                beginTime: moment().add(-6, "h"),
                endTime: moment(),
                current: 1,
                size: 20,
            },
            // 图表弹框查询表单
            echartsFrom: {
                cn: "2011",
                mn: "",
                sampleType: "",
                beginTime: moment().add(-6, "h"),
                endTime: moment(),
                current: 1,
                size: 10000,
            },
            timeCheck: [], // 时间数据
          api:"MonitorgetMonitorHistoryData",
          monitorData:[],   // 表头数据
        };
    },
    methods: {
      openFaultReport(){
        this.$refs.faultreport.isFaultReport = true;
        this.$refs.faultreport.faultData = JSON.parse(JSON.stringify(this.faultData));
        this.$refs.faultreport.init()
      },
        sousuo() {
            this.tableFrom.cn = this.echartsFrom.cn;
            this.tableFrom.beginTime = this.echartsFrom.beginTime;
            this.tableFrom.endTime = this.echartsFrom.endTime;
            this.tableFrom.current = 1;
            this.getTableData();
            this.getEchartsData();
        },
        // 警告类型change事件
        radioChange(e) {
            this.echartsFrom.sampleType = e.target.value;
            this.getEchartsData();
        },
        // 关闭弹窗回调
        cloEchartsFn() {
            this.isEcharts = false;
            this.isloading = true;
            this.total = 0;
            this.tableFrom = {
                cn: "2011",
                mn: "",
                beginTime: moment().add(-6, "h"),
                endTime: moment(),
                current: 1,
                size: 20,
            };
            // 图表弹框查询表单
            this.echartsFrom = {
                cn: "2011",
                mn: "",
                sampleType: "",
                beginTime: moment().add(-6, "h"),
                endTime: moment(),
                current: 1,
                size: 10000,
            };
        },
        // 分页方法
        itemRender(current, type, originalElement) {
            if (type === "prev") {
                return <a> 上一页 </a>;
            } else if (type === "next") {
                return <a> 下一页 </a>;
            }
            return originalElement;
        },
        pagechangeFn(page, pageSize) {
            this.tableFrom.current = page;
            this.getTableData();
        },
        // 日期方法
        disabledStartDate(startValue) {
            const endValue = this.echartsFrom.endTime;
            if (!startValue || !endValue) {
                return false;
            }
            return startValue.valueOf() > endValue.valueOf();
        },
        disabledEndDate(endValue) {
            const startValue = this.echartsFrom.beginTime;
            if (!endValue || !startValue) {
                return false;
            }
            return startValue.valueOf() >= endValue.valueOf();
        },
        handleStartOpenChange(open) {
            if (!open) {
                this.endOpen = true;
            }
        },
        handleEndOpenChange(open) {
            this.endOpen = open;
        },
        // 日期方法完
        // 图表
        lineEcharFn() {
            // this.myCharts.clear();
            let lineData = [];
            let timeData = [];
            // console.log(this.echartsData);

            this.echartsData.forEach((v) => {
              let dataobj = {
                value: v.factorsDataList[0].value,
                symbol: "rect",
                itemStyle: {
                  color: "#40a9ff",
                },
              };
                lineData.push(dataobj);
                timeData.push(moment(parseInt(v.datetime)).format("MM/DD HH:mm:ss"));
            });
            console.log(lineData,timeData)
            let shadowData = [
                {
                    // yAxis: max,
                    // symbol: 'circle',
                    label: {
                        show: true,
                        position: "end",
                        formatter: "最大值",
                    },
                    lineStyle: {
                        color: "#359842",
                    },
                },
                {
                    // symbol: 'circle',
                    label: {
                        show: true,
                        position: "start",
                        formatter: "{c}",
                    },
                    lineStyle: {
                        color: "#359842",
                    },
                },
            ];
            // var color = ["#16fb93", "#ffffff", "#76b2e5"];
            this.myCharts.setOption({
                //提示框组件
                tooltip: {
                    trigger: "axis",
                    show: true,
                    axisPointer: {
                        lineStyle: {
                            color: "#207064",
                        },
                    },
                    // formatter:"{b} </br> {c}"+unit
                    formatter: function (params) {
                        var res = "";
                        for (var i = 0; i < params.length; i++) {
                            res +=
                                params[i].name +
                                "<br/>" +
                                params[i].marker +
                                params[i].value
                        }
                        return res;
                    },
                },
                grid: {
                    top: 40,
                    left: 40,
                    bottom: "35%",
                    right: 40,
                },
                xAxis: {
                    name: "日期",
                    nameGap: 5,
                    nameTextStyle: {
                        color: "#40a9ff",
                        fontSize: 16,
                    },
                    textStyle: {
                        color: "red",
                    },
                    data: timeData,
                    min: (value) => {
                        return Math.round(value.min);
                    },
                    // axisLine: {
                    //     lineStyle: {
                    //         color: "#207064",
                    //     },
                    // },
                    //x轴坐标的旋转
                    axisLabel: {
                        rotate: 45,
                    },
                },
                yAxis: {
                    //y轴字体颜色
                    // name: unit,
                    nameGap: 10,
                    nameTextStyle: {
                        // color: "#37ddc0",
                        fontSize: 16,
                    },
                    // axisLabel: {
                    //     color: "#207064",
                    // },
                    // max: (value) => {
                    //     return parseInt(_max)

                    // },
                    min: (value) => {
                        return value.min;
                    },
                    splitLine: {
                        show: true,
                        //设置y轴的坐标轴刻度设置为虚线和颜色
                        lineStyle: {
                            type: "dashed",
                            // color: "#207064",
                        },
                    },
                    //y轴颜色
                    // axisLine: {
                    //     lineStyle: {
                    //         color: "#207064",
                    //     },
                    // },
                },
                dataZoom: [
                    {
                        show: true,
                        height: 12,
                        xAxisIndex: [0],
                        bottom: 0,
                        start: 100,
                        end: 70,
                        handleIcon:
                            "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
                        handleSize: "110%",
                        handleStyle: {
                            color: "#d3dee5",
                        },
                        textStyle: {
                            color: "#40a9ff",
                        },
                        borderColor: "#90979c",
                    },
                    {
                        type: "inside",
                        show: true,
                        height: 15,
                        start: 1,
                        end: 35,
                    },
                ],
                series: [
                    {
                        type: "line",
                        symbol: "rect",
                        symbolSize: 10,
                        data: lineData,
                        //平滑曲线
                        smooth: true,
                        // 普通样式
                        itemStyle: {
                            // 点的颜色
                            color: "#40a9ff",
                        },
                    },
                ],
            });
            this.myCharts.hideLoading();
            window.addEventListener("resize", () => {
                this.myCharts.resize();
            });
        },
        // 获取图表数据方法
        getTableData() {
            let timeData = JSON.parse(JSON.stringify(this.tableFrom));
            timeData.beginTime = new Date(timeData.beginTime).getTime();
            timeData.endTime = new Date(timeData.endTime).getTime();
            // console.log(timeData);
            this.$api.MonitorgetMonitorHistoryData(timeData).then((res) => {
                if (res.data.code == 0) {
                    // console.log(res.data.data);
                    this.total = res.data.total;
                    res.data.data.forEach(v=>{
                      v.datetime = moment(parseInt(v.datetime)).format("YYYY-MM-DD HH:mm:ss");
                      v.factorsDataList.forEach(item=>{
                        v[item.code] = item.zsValue?item.value+"折"+item.zsValue:item.value;
                      })
                    })
                    this.TableData = res.data.data;
                } else {
                    this.TableData = [];
                }
                this.isloading = false;
            });
        },
        getEchartsData() {
            this.$nextTick(() => {
                this.myCharts = echarts.init(this.$refs.lineecharts);
                this.myCharts.showLoading({
                    text: "正在加载中。。。",
                    maskColor: "rgba(255, 255, 255, 0.8)",
                    color: "#1890ff",
                    textColor: "#000",
                });
            });
            let timeData = JSON.parse(JSON.stringify(this.echartsFrom));
            timeData.beginTime = new Date(timeData.beginTime).getTime();
            timeData.endTime = new Date(timeData.endTime).getTime();
            this.$api.MonitorgetMonitorHistoryData(timeData).then((res) => {
                if (res.data.code == 0) {
                    console.log(res.data);
                    if (res.data.data.length <= 0) {
                        this.$message.warning("暂无数据！");
                    }
                    this.echartsData = res.data.data;
                    this.lineEcharFn();
                } else {
                    this.$message.warning(res.data.errorMessage);
                }
            });
        },
        async init(id) {
            await this.getThead(id)
            await this.getEchartsData();
            await this.getTableData();
            // this.$api.getEquipmentCnByEquipmentId(id).then((res) => {
            //     if (res.data.code == 0) {
            //         this.timeCheck = res.data.data;
            //         this.echartsFrom.cn = res.data.data[0].cn;
            //         this.tableFrom.cn = res.data.data[0].cn;
            //
            //     }
            // });
          // this.$api.
        },
      getThead(id){
        this.$api.monitorFactorsFindByMonitorId(id).then(res=>{
          if(res.data.code === 0){
            res.data.data.forEach(v=>{
              v.unit = v.unit?v.unit:"-"
            })
            this.monitorData = res.data.data;
          }else {
            this.$message.info(res.data.errorMessage)
          }
        })
      }
    },
    watch: {
        "echartsFrom.cn": {
            deep: true,
            handler(newVal) {
                switch (newVal) {
                    case "2011":
                        this.echartsFrom.beginTime = moment().add(-6, "h");
                        break;
                    case "2051":
                        this.echartsFrom.beginTime = moment().add(-6, "h");
                        break;
                    case "2061":
                        this.echartsFrom.beginTime = moment().add(-15, "days");
                        break;
                    case "2031":
                        this.echartsFrom.beginTime = moment().add(-30, "days");
                        break;
                }
            },
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep .ant-modal-body {
    padding: 0 20px 20px;
}

.echar-table {
    height: 330px;
  ::v-deep .ant-table-wrapper .ant-table-fixed-header .ant-table-scroll .ant-table-header{
    //margin-bottom: 0!important;
    overflow: hidden!important;
  }
}

// 分页
.page-box {
    float: right;
}

/* 图表 */
.line-echarts {
    width: 100%;
    height: 300px;
}

.echarts-title {
    font-weight: 600;
    color: rgba(255, 255, 255, 0.8);
    text-align: center;
    padding: 10px 0;
    box-sizing: border-box;
}
</style>